package org.qiyu.live.im.core.server.handler.Impl;

import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.qiyu.live.im.core.server.common.ImContextUtils;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.handler.SimplyHandler;
import org.qiyu.live.im.topic.ImCoreServerProviderTopicNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Description: 业务消息处理器
 * @Author: 张广焱
 * @Date: 2023-12-03 13:16
 */@Component
public class BizImMsgHandler implements SimplyHandler {
     private static final Logger logger = LoggerFactory.getLogger(BizImMsgHandler.class);
     @Resource
     private MQProducer mqProducer;
    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg imMsg) {
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if (userId == null || appId == null) {
            logger.error("attr is error");
            ctx.close();
            throw new IllegalArgumentException("attr is error");
        }
        byte[] body = imMsg.getBody();
        if (body==null||body.length==0){
            logger.error("body is null");
            return;
        }
        //发送消息到mq 把消息投递出去
        Message message = new Message();
        message.setTopic(ImCoreServerProviderTopicNames.QIYU_LIVE_IM_BIZ_MSG_TOPIC);
        message.setBody(body);
        try {
            SendResult send = mqProducer.send(message);
            logger.info("send result is {}",send);
        } catch (Exception e) {
            logger.error("send error",e);
            throw new RuntimeException(e);
        }
    }
}
